<!DOCTYPE html>
<html lang="zh-cn">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>javascript 阶段</title>
    <style>
        .box {
            width: 100px;
            height: 100px;
            background-color: red;
        }

        .button {
            padding: 10px 20px;
            cursor: pointer;
        }
    </style>
</head>

<body>
    <div class="box"></div>
    <button class="button">点击按钮</button>


    <script>
        // 1.0 获取相关的标签
        var box = document.querySelector(".box");
        var button = document.querySelector(".button");
        // 2.0 动画函数
        var timer = null;
        var move = function () {
            timer = setInterval(function () {
                var cur = parseInt(getComputedStyle(box)["marginLeft"]);
                var speed = 10;
                if (cur >= 500) {
                    clearInterval(timer);
                    console.log("到达目标位置!",cur);
                    return;
                }
                box.style["marginLeft"] = cur + speed + "px";
            }, 500)
        }
        // 3.0 事件绑定
        button.onclick = function() {
            // 防抖逻辑（如果不编写这行代码，然后疯狂点击按钮，出现定时器停止不了的现象）
            // clearInterval(timer);
            // 执行动画函数(move函数中的代码被频繁执行)
            move();
        }


    </script>
</body>

</html>